
// 获取菜单栏元素，根据点击的元素显示相应页面并运行对应函数
document.querySelectorAll('.sidebar a').forEach(link => {
    if (!sessionStorage.getItem('nickname')) {
        window.location.href = "/login.html";
        return;
    }
    link.addEventListener('click', function(event) {
        event.preventDefault();
        const targetId = this.getAttribute('data-target');

        document.querySelectorAll('.content').forEach(div => {
            div.classList.remove('active');
        });

        const targetDiv = document.getElementById(targetId);
        targetDiv.classList.add('active');
        switch(targetId){
            case "1":
                break;
            case "2":
                targetDiv.querySelectorAll('input[type="password"]').forEach(input => {
                    input.value = '';
                });
                break;
            case "3":
                document.querySelectorAll('.amount').forEach(a => a.classList.remove('active'));
                break;
            case "4" :
                getAddress();
                break;
            case "5":
                showOrders();
                break;
        }
    });
});

// 窗口运行完毕显示用户信息
window.onload = function() {
    document.getElementById("username").textContent = sessionStorage.getItem("nickname");
    document.getElementById("name").textContent = sessionStorage.getItem("nickname");
    document.getElementById("userImage").src = sessionStorage.getItem("image");
    document.getElementById("userID").textContent = "用户id：" + sessionStorage.getItem("userid");
    document.getElementById("userAccount").textContent = "用户账号：" + sessionStorage.getItem("account");
    document.getElementById("allBalance").textContent = "余额：￥" + sessionStorage.getItem("balance") + " ";
    document.getElementById("userAmount").textContent = "余额：￥" + sessionStorage.getItem("balance") + " ";
    showOrdersCount();
    showUserInfo();
}

// 获取订单总数
function showOrdersCount() {
    $.ajax({
        url:"/orders",
        method:"get",
        data:{type:"count", userId: sessionStorage.getItem("userid")},
        success: function (dataString) {
            document.getElementById("orderCount").textContent = "订单：" + dataString + "已完成";
        }
    })
}

// 前往管理订单
document.getElementById('goToOrders').addEventListener('click', function(event) {
    event.preventDefault();
    // 订单管理的 data-target 值
    const targetId = '5';
    document.querySelectorAll('.content').forEach(div => {
        div.classList.remove('active');
    });
    // 运行订单管理的函数
    const targetDiv = document.getElementById(targetId);
    targetDiv.classList.add('active');
    document.querySelectorAll('.amount').forEach(a => a.classList.remove('active'));
});

// 前往充值
document.getElementById('gotoRecharge').addEventListener('click', function(event) {
    event.preventDefault();
    // 订单管理的 data-target 值
    const targetId = '3';
    document.querySelectorAll('.content').forEach(div => {
        div.classList.remove('active');
    });
    // 运行订单管理的函数
    const targetDiv = document.getElementById(targetId);
    targetDiv.classList.add('active');
    showOrders();
});

// 打开弹窗逻辑
document.querySelectorAll('.goto').forEach(link => {
    link.addEventListener('click', function(event) {
        event.preventDefault();
        document.getElementById("userInfoModal").style.display = 'block';
    });
});

// 关闭弹窗逻辑
document.querySelectorAll('.close').forEach(span => {
    span.addEventListener('click', function() {
        this.parentElement.parentElement.style.display = 'none';
    });
});

window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
}

// 更新电话和邮箱
document.getElementById('save').addEventListener('click', function() {
    const newPhone = document.getElementById('newPhone').value;
    const phonePattern = /^[0-9]{10,11}$/; // 简单的电话号码验证
    const newEmail = document.getElementById('newEmail').value;
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // 简单的邮箱验证
    if (!phonePattern.test(newPhone)) {
        showInfo('请输入有效的电话号码（10到11位数字）');
        return;
    }
    if (!emailPattern.test(newEmail)) {
        showInfo('请输入有效的邮箱地址');
        return;
    }
    $.ajax({
        url: "/userInfo",
        method:"get",
        data:{type:"update",phone:newPhone,email:newEmail,id:sessionStorage.getItem("userid")},
        success: function(data) {
            if (data === "success") {
                showInfo("更新成功");
                showUserInfo();
            }
        }
    })
});

// 展示电话和邮箱
function showUserInfo(){
    $.ajax({
        url:"/userInfo",
        method:"get",
        data:{type:"select",id:sessionStorage.getItem("userid")},
        dataType:"json",
        success:function(dataString){
            if (dataString != null) {
                const data = JSON.parse(dataString);
                document.getElementById("email").textContent = data.email;
                document.getElementById("phone").textContent = data.phone;
            }
        }
    })
}

// 注销登录
function logout() {
    window.location.href = 'login.html';
}

// 更新密码
function updatePassword() {
    const OPassword = document.getElementById("OPassword").value;
    const CPassword = document.getElementById("CPassword").value;
    const CRPassword = document.getElementById("CRPassword").value;
    if (OPassword === "" || CPassword === "" || CRPassword === "") {
        showInfo("请填写完整！");
        return;
    }
    $.ajax({
        url:"/password",
        method: "get",
        data: {'type':"get", 'id': sessionStorage.getItem("id")},
        success: function (dataString) {
            const data = JSON.parse(dataString);
            if (data[0] === OPassword) {
                $.ajax({
                    url:"/password",
                    method: "get",
                    data: {'type':"update", 'id': sessionStorage.getItem("userid"), password:CPassword},
                    success:function (dataString) {
                        if (CPassword !== CRPassword) {
                            showInfo("重复密码不一致！");
                            return;
                        }
                        if (dataString === "success") {
                            showInfo("修改成功");
                        } else {
                            showInfo("修改失败");
                        }
                    },
                    error: function (){
                        showInfo("服务器错误");
                    }
                })
            } else {
                showInfo("原密码错误");
            }
        },
        error: function (){
            showInfo("服务器错误");
        }
    })
}

// 金额选择高亮
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.amount').forEach(amount => {
        amount.addEventListener('click', function() {
            // 移除所有预设金额的高亮
            document.querySelectorAll('.amount').forEach(a => a.classList.remove('active'));
            // 清空自定义金额输入框
            document.getElementById('customAmount').value = '';
            // 高亮当前点击的预设金额
            this.classList.add('active');
        });
    });

    document.getElementById('customAmount').addEventListener('focus', function() {
        // 移除所有预设金额的高亮
        document.querySelectorAll('.amount').forEach(a => a.classList.remove('active'));
    });

});

// 获取选中的预设金额或者自定义金额跳转充值
function recharge() {
    let selectedAmount = null;
    // 检查是否有预设金额被选中
    document.querySelectorAll('.amount').forEach(amount => {
        if (amount.classList.contains('active')) {
            selectedAmount = parseInt(amount.getAttribute('data-amount'));
        }
    });

    // 如果没有预设金额被选中，检查自定义金额
    if (!selectedAmount) {
        selectedAmount = parseInt(document.getElementById('customAmount').value);
    }

    if (selectedAmount) {
        sessionStorage.setItem("goodsName","余额充值");
        sessionStorage.setItem("current price",selectedAmount);
        sessionStorage.setItem("amountType","1");
        window.location.href = "buy.html";
    } else {
        showInfo("请选择或输入充值金额");
    }
}

// 展示订单信息
function showOrders() {
    $.ajax({
        url:"/orders",
        method: "get",
        data: {type:"get",value:"0", userId: sessionStorage.getItem("userid")},
        dataType: "json",
        success: function (dataString){
            const jsonStringArray = JSON.parse(dataString);
            const data = jsonStringArray.map(item => JSON.parse(item));
            const contentElement = document.getElementById("5");
            const fragment = document.createDocumentFragment();
            contentElement.innerHTML = "";
            for (let i = 0; i < data.length; i++) {
                let status;
                let buttonTitle;
                let onclick;
                if (data[i].state === "1") {
                    status = "<span class=\"paid\">已支付</span>";
                    buttonTitle = "申请退款";
                    onclick = "applyRefund(" + data[i].id + "," + data[i].price + "," + data[i].number + ")";
                } else if (data[i].state === "2") {
                    status = "<span class=\"unpaid\">未支付</span>";
                    buttonTitle = "立即支付";
                    onclick = "pay(" + data[i].id + "," + data[i].price + "," + data[i].name + ")";
                } else if (data[i].state === "3") {
                    status = "<span class=\"refund\">退款中</span>";
                    buttonTitle = "取消退款";
                    onclick = "cancelRefund(" + data[i].id + ")";
                } else if (data[i].state === "4") {
                    status = "<span class=\"refunded\">已退款</span>";
                    buttonTitle = "重新购买";
                    onclick = "buyAgain(" + data[i].id + ")";
                } else if (data[i].state === "5") {
                    status = "<span class=\"canceled\">已取消</span>";
                    buttonTitle = "重新购买";
                    onclick = "buyAgain(" + data[i].id + ")";
                }
                const htmlContent = `
                    <div class="card">
                        <div class="order-info">
                            <img src=${data[i].image} alt="商品图片">
                            <div class="order-details">
                                <div class="order-title">
                                    <span style="width: 700px">${data[i].name}</span>
                                    <span${status}</span>
                                </div>
                                <div class="order-quantity">购买数量: ${data[i].number}</div>
                                <div class="order-amount">实付款: ￥${data[i].price}</div>
                                <div class="order-time">订单号：${data[i].id} | 订单时间: ${data[i].time}</div>     
                           </div>
                        </div>
                        <div class="order-actions">                     
                            <button onclick="deleteOrders(${data[i].id})">删除订单</button>
                            <button onclick="${onclick}">${buttonTitle}</button>
                        </div>
                    </div>
                `;
                const tempElement = document.createElement('div');
                tempElement.innerHTML = htmlContent;
                fragment.appendChild(tempElement.firstElementChild);
            }
            contentElement.appendChild(fragment);
        }
    })
}

// 删除订单信息
function deleteOrders(id) {
    $.ajax({
        url:"orders",
        type:"get",
        data:{type:"delete",userId:sessionStorage.getItem("userid"),id:id},
        success:function (data) {
            if (data === "success") {
                showInfo("删除成功");
                showOrders();
            }
        }
    })
}

// 申请退款
function applyRefund(id,price) {
    $.ajax({
        url:"orders",
        type:"get",
        data:{type:"update",userId:sessionStorage.getItem("userid"),id:id,state:4},
        success:function (data) {
            if (data === "success") {
                const balance = parseFloat(sessionStorage.getItem("balance")) + parseFloat(price);
                $.ajax({
                    url: '/balance',
                    method: "get",
                    data: {allBalance: balance, id: sessionStorage.getItem("userid")},
                    dataType: "text",
                    success: function (data) {
                        if (data === "success") {
                            showInfo("退款成功");
                            sessionStorage.setItem("balance", balance);
                        }
                    }
                })
                showOrders();
            }
        }
    })
}

// 重新购买
function buyAgain(id) {
    sessionStorage.setItem("id",id);
    window.location.href = "info.html";
}

// 未支付订单前往支付
function pay(id,price,name,number){
    sessionStorage.setItem("orderId",id);
    sessionStorage.setItem("current price",price);
    sessionStorage.setItem("goodsName",name);
    sessionStorage.setItem("amountType","3");
    sessionStorage.setItem("number",number);
    window.location.href = "buy.html";
}

// 取消退款
function cancelRefund(id) {
    $.ajax({
        url:"orders",
        type:"get",
        data:{type:"update",userId:sessionStorage.getItem("userid"),id:id,state:1},
        success:function (data) {
            if (data === "success") {
                showInfo("取消成功");
                showOrders();
            }
        }
    })
}